package com.atguigu.gmall.order.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.cart.client.CartFeignClient;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.service.OrderInfoService;
import com.atguigu.gmall.user.client.UserFeigClient;
import io.swagger.annotations.ApiOperation;
import jodd.util.CollectionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/order")
public class OrderApiController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserFeigClient userFeigClient;

    @Autowired
    private CartFeignClient cartFeignClient;


    @Autowired
    private OrderInfoService orderInfoService;

    @ApiOperation("结账")
    @GetMapping("/trade")
    public Map<String,Object> trade(HttpServletRequest request){
        Map<String,Object> result =null;
        List<CartInfo> cartListChecked = cartFeignClient.getCartListChecked();
        if(!CollectionUtils.isEmpty(cartListChecked)){
            result = new HashMap<>();
            String tradeNo = UUID.randomUUID().toString().replaceAll("-", "");
            result.put("tradeNo",tradeNo);
            String userId = AuthContextHolder.getUserId(request);
            redisTemplate.opsForValue().set("tradeNo"+userId,tradeNo);
            List<UserAddress> userAddressList = userFeigClient.userAddressList();
            result.put("userAddressList",userAddressList);

            List<OrderDetail> orderDetailList = cartListChecked.stream().map(cartInfo -> {
                OrderDetail detail = new OrderDetail();
                detail.setImgUrl(cartInfo.getImgUrl());
                detail.setSkuName(cartInfo.getSkuName());
                detail.setOrderPrice(cartInfo.getSkuPrice());
                detail.setSkuNum(cartInfo.getSkuNum());
                detail.setSkuId(cartInfo.getSkuId());
                return detail;
            }).collect(Collectors.toList());
            result.put("detailArrayList",orderDetailList);

            //2:总件数
            long totalNum = orderDetailList.stream().collect(
                    Collectors.summarizingInt(OrderDetail::getSkuNum)).getSum();
            result.put("totalNum",totalNum);

            //3:总金额
            BigDecimal totalAmount = new BigDecimal("0");
            for (OrderDetail orderDetail : orderDetailList) {
                BigDecimal orderPrice = orderDetail.getOrderPrice();
                totalAmount = totalAmount.add(orderPrice.multiply(new BigDecimal(orderDetail.getSkuNum())));
            }
            result.put("totalAmount",totalAmount);
        }


        return result;

    }

    @ApiOperation("提交订单")
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo,String tradeNo,HttpServletRequest request){
        //校验交易号是否正确，防止二次提交
        String userId = AuthContextHolder.getUserId(request);
        Object o = redisTemplate.opsForValue().get("tradeNo" + userId);
        //如果没有 已经提交过了
        if(StringUtils.isEmpty(tradeNo)){
            return Result.fail().message("非法操作");
        }
        if(o==null){
            return Result.fail().message("请不要重复提交");
        }else if(!tradeNo.equals(o)) {
            return Result.fail().message("非法操作");
        }
        redisTemplate.delete("tradeNo" + userId);
        //校验库存 远程调用仓库系统
        //购买数量小于库存

        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        //判断是否为空
        if(CollectionUtils.isEmpty(orderDetailList)){
            return Result.fail().message("非法操作，请添加商品结算");
        }
        //遍历查看库存是否充足
        for (OrderDetail orderDetail : orderDetailList) {
            boolean flag=orderInfoService.hasStock(orderDetail.getSkuId(),orderDetail.getSkuNum());
            if(!flag){
                return Result.fail().message(orderDetail.getSkuName()+"库存不足");
            }
        }

        orderInfo.setUserId(Long.parseLong(userId));
        //保存
        Long orderId=orderInfoService.submitOrder(orderInfo);
        return Result.ok(orderId);
    }

    @ApiOperation("获取订单信息")
    @GetMapping("/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable Long orderId){
        return orderInfoService.getOrderInfo(orderId);
    }

    //由仓库发出Http请求 要求折单
    @PostMapping("/orderSplit")
    public String orderSplit(Long orderId,String wareSkuMap){

        //TODO 1查询仓库系统  拆单接口说明  具体代码

        List<Map<String,Object>> listMap=orderInfoService.orderSplit(orderId,wareSkuMap);
        return JSONObject.toJSONString(listMap);
    }
}
